package com.yellow.cloud.system.listener;

import com.rabbitmq.client.Channel;
import com.yellow.cloud.system.mapper.SysDetailLogMapper;
import com.yellow.cloud.system.mapper.SysOperateLogMapper;
import com.yellowframework.cloud.config.RabbitmqConfig;
import com.yellowframework.cloud.domain.system.SysDetailLog;
import com.yellowframework.cloud.domain.system.SysOperateLog;
import com.yellowframework.cloud.domain.system.request.SysDetailLogRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 监听操作日志
 * @author Hao.
 * @version 1.0
 * @since 2023/6/28 16:54
 */
@Slf4j
@Component
@RabbitListener(queues = RabbitmqConfig.QUEUE_INFORM_LOG)
public class LogListener {

    @Resource
    private SysOperateLogMapper operateLogMapper;

    @Resource
    private SysDetailLogMapper detailLogMapper;

    @RabbitHandler
    public void handleOperateLog(SysOperateLog operateLog, Message message, Channel channel) throws IOException {
        log.info("******收到添加操作日志的信息******");
        try {
            operateLogMapper.insert(operateLog);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            // 操作日志添加失败 将消息重新放回队列，让别人消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitHandler
    public void handleDetailLog(SysDetailLogRequest request, Message message, Channel channel) throws IOException {
        log.info("******收到添加详细日志的信息******");
        try {
            final SysOperateLog operateLog = request.getSysOperateLog();
            final SysDetailLog detailLog = request.getSysDetailLog();
            operateLogMapper.insert(operateLog);
            detailLog.setLogId(operateLog.getId());
            detailLogMapper.insert(detailLog);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            // 详细日志添加失败 将消息重新放回队列，让别人消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
